import string
import serial
import time
import numpy as np
import pandas as pd
from datetime import datetime
import json
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

with open("current\current9.txt","r") as f:
    data = f.read()
    # print(data)
    print(type(data))
    a = data.split()
    print(a)
current_list=[]

count = len(a)
print(count)
for i in range(0, count-1, 2):
    current = int(a[i],16)*256 + int(a[i+1],16)
    if(current >= 32768):
        current = current - 65536
    # if(current >= 1000 or current <=-1000):
    #     current = 0
    current_list.append(current)


length = len(current_list)

current_list1=[0 for i in range(length)]
current_list2=[0 for i in range(length)]

# for i in range(len(current_list)):
#     if(i>=64):
#         if(abs(current_list[i]-current_list[i-64]) >= 500):
#             current_list[i]=current_list[i-64]

lower_limit = np.percentile(current_list, 0.5)
upper_limit = np.percentile(current_list, 99.5)
print(lower_limit, upper_limit)
for i in range(len(current_list)):
    if(current_list[i] >= upper_limit or current_list[i] <= lower_limit):
        if(i>=64):
            current_list1[i]=current_list1[i-64]
        else:
            current_list1[i] = 0.5*(current_list[i-1]+current_list[i+1])
    else:
        current_list1[i]= current_list[i]

lower_limit = np.percentile(current_list1, 0.01)
upper_limit = np.percentile(current_list1, 99.99)
print(lower_limit, upper_limit)
for i in range(len(current_list)):
    if(current_list1[i] >= upper_limit or current_list1[i] <= lower_limit):
        current_list2[i] = 0.5*(current_list1[i-1]+current_list1[i+1])
    else:
        current_list2[i] = current_list1[i]

for j in range(13):
    lower_limit = np.percentile(current_list[j*3200:(j+1)*3200], 0.5)
    upper_limit = np.percentile(current_list[j*3200:(j+1)*3200], 99.5)
# print(current_list)
ave = np.mean(current_list)
# current_list2 = [x-ave for x in current_list]
error_list=[current_list[i]-current_list2[i] for i in range(length)]

t = range(len(current_list2))
fig=plt.figure(figsize=(5,4))
plt.title('测量数据暂态变化曲线')  # 设置标题
# plt.plot(t,current_list,alpha = 0.5,marker='o',markersize=5)
plt.plot(t,current_list)
# plt.plot(t,error_list)
plt.show()
dic0 = dict(zip(t,current_list))
dic3 = dict(zip(t,current_list1))
dic1 = dict(zip(t,current_list2))
dic2 = dict(zip(t,error_list))
# write_dict('test.txt',dic1)
# dic2 = read_dict('data_of_kettle.txt')
series0 = pd.Series(dic0)
series1 = pd.Series(dic1)
series2 = pd.Series(dic2)
series3 = pd.Series(dic3)

# series1.to_csv('test62_0.csv')
# series2.to_csv('error_test62_0.csv')

d = {'before':series0,'after':series1,'error':series2}
df = pd.DataFrame(d)

df.to_csv(f'lvbo{datetime.now().strftime("%m_%d_%H_%M_%S")}.csv')
# series1.to_csv(f'test{int(1000*time.time())}.csv')